<template>
  <div id="canvas_main" :style='{width:width+"px",height:height+"px",cursor: cursor}'>   
    <!-- <div class="log">
        当前点位: {{tempCurrent.data.subscript || '无'}} 
    </div>  -->
  </div>
</template>

<script> 
const range = 23, pointImage = new Image()

function S4() {
    return (((1+Math.random()) * 0x10000) | 0).toString(16).substring(1);
}
function guid() {
    return S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4();
}
function isPlainObject(obj) {
    return Object.prototype.toString.call(obj) === '[object Object]'
}

export default { 
  props: {
    points: {
      type: Array,
      required: true
    },
    imageUrl: {
      type: String,
      required: true
    },
    pushPoint: {
      type: Boolean,
      required: false,
      default: true
    }
  },
  watch: {
    points: 'init'
  },
  data () {
    return {
      height: 800,
      width: 800,
      cursor: 'default'
    }
  },

  methods: {
    init() { 
      //放大比例
      this.scale = 1 
      this.imagePoint = {}
      this.main = document.getElementById('canvas_main')  
      pointImage.src = ''
      //init background image
      let img = new Image()
        img.src = this.imageUrl
        img.onload = e => { 
          this.width = img.width
          this.height = img.height 


          let canvas = this.createLayer()
          canvas.addEventListener('click', function (e) {
            console.log(e)
          }) 
          this.imageParams = {
            canvas: canvas,
            image: img
          }
          //init points
          this.pointParams = this.points.map(point => {
            let canvas = this.createLayer()
            return {
              canvas: canvas,
              ...point
            }
          })
          this.drawBackground(this.imageParams)
          this.drawPoints(this.pointParams) 
        } 
      
    }, 
    drawBackground(params) {
      let context = params.canvas.getContext('2d')
      context.setTransform(this.scale, 0, 0, this.scale, 0, 0)
      context.drawImage(params.image, 0, 0, this.width,  this.height)
    },
    drawPoints(params) {
      params.map(el => { 
          let x = parseInt(el.x);
          let y = parseInt(el.y);
          let context = el.canvas.getContext('2d')
          context.font="18px Georgia"
          context.fillStyle = "white"
          context.setTransform(this.scale, 0, 0, this.scale, 0, 0)
          context.drawImage(pointImage, x - range, y  - range * 2, 45, 45)
          context.fillText((typeof el.label!=='undefined')?el.label:'', x - 5, y- range);
      })
    }, 
    createLayer() {
      let canvas = document.createElement("canvas") 
      canvas.id = 'm' + guid() 
      canvas.style.position = 'absolute'
      canvas.style.left = 0
      canvas.style.top = 0
 
      canvas.width = this.width
      canvas.height = this.height

      this.main.appendChild(canvas)
      return canvas
    },

    // draw(canvas, x, y, data) {   
    //   let context = canvas.getContext('2d')
    //   context.setTransform(this.ratio, 0, 0, this.ratio, 0, 0)

    //   context.fillStyle="#FF0000";
    //   context.beginPath(); 
    //   //x,y,r
    //   context.arc(x, y, 16, 0, Math.PI * 2, true);
    //   context.closePath();
    //   context.fill(); 
    //   if (data) {
    //     context.font="16px Arial";
    //     context.fillStyle="black";
    //     context.fillText(data.subscript, x - 10, y + 7);
    //   }
    //   this.imagePoint[canvas.id] = {
    //     leftX: x - 50, 
    //     leftY: y - 50, 
    //     rightX: x + 50, 
    //     rightY: y + 50, 
    //     canvas: canvas,
    //     data: data 
    //   }
    // },

    findLayer(x, y) { 
      for (let point of this.pointParams) { 
        if (point.x - range <= x && point.y - range * 2 <= y && point.x + range >= x && point.y + range * 2 >= y)
          return point
      } 
      return null
    },

    delPoint(canvas) {
      let context = canvas.getContext('2d')
      context.clearRect(0, 0, this.width, this.height);  
    },

    redraw(params) {  
      console.log(1)
      this.delPoint(params.canvas)
      this.drawPoints([params])
    },

    // draw$p1(page) { 
    //   if (this.canResize != void 0 && !this.canResize)
    //     return

    //   this.canResize = false
    //   let canvas, ctx, ratio
    //   if (this.page) {
    //     canvas = this._canvas
    //     ctx = this._ctx
    //     ratio = this._ratio
    //   } else {
    //     this._canvas = canvas = this.createLayer()
    //     this._ctx = ctx = canvas.getContext('2d')
        
    //     let dpr = window.devicePixelRatio || 1
    //     let bsr = ctx.webkitBackingStorePixelRatio 
    //       || ctx.mozBackingStorePixelRatio 
    //       || ctx.msBackingStorePixelRatio 
    //       || ctx.oBackingStorePixelRatio 
    //       || ctx.backingStorePixelRatio 
    //       || 1
          
    //     this._ratio = ratio = dpr / bsr
    //   } 

    //   let viewport = page.getViewport(screen.availWidth / page.getViewport(this.scale).width)
    //   canvas.width = viewport.width * ratio 
    //   canvas.height = viewport.height * ratio 
    //   canvas.style.width = viewport.width  + 'px'
    //   canvas.style.height = viewport.height  + 'px'
    //   ctx.setTransform(ratio, 0, 0, ratio, 0, 0)
    //   this.ratio = ratio
    //   this.canvasStyle =  { 
    //     width: canvas.width,
    //     height: canvas.height,
    //     style: {
    //       width: canvas.style.width,
    //       height: canvas.style.height
    //     }
    //   }
    //   var img=new Image()
    //   img.src = "../assets/back2.png"
    //   this._ctx.drawImage(image, 0, 0)
    //   let renderContext = {
    //     canvasContext: ctx,
    //     viewport: viewport
    //   }
    //   var renderTask = page.render(renderContext) 
    //   renderTask.promise.then(res => {
    //     this.canResize = true
    //   })
      
    //   this.initPoint(this.list)
    // },

    // loadPdf$p1(url) {

    //   let canvas = this.createLayer()
    //   if (this.page) {
    //     this.draw$p1(this.page)
    //   } else {
    //     PDFJS.getDocument(url).then((pdf) => {
    //       pdf.getPage(1).then(page => {
    //         this.draw$p1(page)
    //         this.page = page
    //       })
    //     }) 
    //   }
    // },

    // resize(scale) {
    //   if (scale == this.scale)
    //     return

    //   this.scale = scale
    //   this.canResize && this.draw$p1(this.page)
    // }
     
  },
  mounted() {
    
    this.init()

    this.main.onmousedown = e => {  
      this.currentCanvas = this.findLayer(e.layerX, e.layerY)  
      if (this.currentCanvas == null) {
        let canvas = this.createLayer()
        let label = 1
        if (this.points.length) {
          label = parseInt(this.points[this.points.length - 1].label || 0) + 1
        }
        let params = {
          canvas: canvas,
          x: e.layerX,
          y: e.layerY,
          label: label
        }
        if(this.pushPoint){
          this.points.push({
            x: e.layerX,
            y: e.layerY,
            label: label
          })
        }
        this.$emit('event', {
          instruction: 'insert-point',
          point: params
        })
        this.pointParams.push(params)
        this.drawPoints([params])
      }else{
        this.cursor = 'pointer'
      }
    }

    this.main.onmousemove = e => { 
      if (this.currentCanvas) {
        this.currentCanvas.canvas.style.cursor = 'pointer'
        this.cursor = 'pointer'
        this.currentCanvas.x = e.layerX
        this.currentCanvas.y = e.layerY
        this.redraw(this.currentCanvas)
      } 
    }

    this.main.onmouseup = e => { 
      if (this.currentCanvas) {
        this.currentCanvas.canvas.style.cursor = 'default'
        this.tempCanvas = this.currentCanvas.canvas
        this.$emit('event', {
          instruction: 'move-point',
          point: this.currentCanvas
        })
        this.cursor = 'default'
        
      }
      this.currentCanvas = null
    } 
    document.onkeydown = () => {
      var e = window.event; 
      if (e.keyCode == 8 || e.keyCode == 46) { 
        this.delPoint(this.tempCanvas)
      } 
      //  else if (e.keyCode == 81) {
        
      //   let scale  = this.scale - 0.4 
      //   this.resize(scale) 
      // } else if (e.keyCode == 87) { 
      //   let scale  = this.scale + 0.4
      //   this.resize(scale)
      // }
    }
  }
}
</script>
<style> 
  #canvas_main{
    position: relative;
  }
  .log {
    position:fixed;
    left: 0;
    right: 0;
    width: 120px; 
    z-index: 10;
    background-color: rgba(0, 0, 0, 0.6);
    color: white; 
    size: 12px; 
    padding: 10px;
    border-top-right-radius: 12px;
    border-bottom-right-radius: 12px;
  }
  .panel {
    position:fixed;
    bottom: 0; 
    height: 140px;
    width: 80%;
    margin-left: 10%;
    background-color: rgba(0, 0, 0, 0.8);
    z-index: 15;
  }
</style>

<!-- Add "scoped" attribute to limit CSS to this component only -->
 